/*
 * @Author: 杰编程 2306248989@qq.com
 * @Date: 2023-07-28 23:02:43
 * @LastEditors: 杰编程 2306248989@qq.com
 * @LastEditTime: 2023-07-29 12:31:17
 * @FilePath: /lesson22/sem/main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include <iostream>

using namespace std;

#include <ctime>

#include <unistd.h>
#include <pthread.h>

#include "ringQueue.hpp"

void *consumerRoutine(void *args)
{
    RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    while (true)
    {
        // 1. 消费者获取任务数据
        int task = 0;
        rq->pop(&task);
        // 2. 消费者处理任务数据
        cout << pthread_self() << "| "
             << "data: " << task << endl;
    }
}

void *producerRoutine(void *args)
{
    RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    while (true)
    {
        // 1. 生产者生产任务数据
        int task = rand() % 10;
        // 2. 生产者推送数据
        rq->push(task);
        cout << pthread_self() << "|"
             << "push data: " << task << endl;
    }
}

int main()
{
    srand((uint64_t)time(nullptr) ^ getpid());
    RingQueue<int> *rq = new RingQueue<int>();
    // pthread_t c, p;
    // pthread_create(&c, nullptr, consumerRoutine, rq);
    // pthread_create(&p, nullptr, producerRoutine, rq);

    // pthread_join(c, nullptr);
    // pthread_join(p, nullptr);

    pthread_t c[3], p[2];
    for (int i = 0; i < 3; i++)
        pthread_create(c + i, nullptr, consumerRoutine, rq);
    for (int i = 0; i < 2; i++)
        pthread_create(p + i, nullptr, producerRoutine, rq);

    for (int i = 0; i < 3; i++)
        pthread_join(c[i], nullptr);
    for (int i = 0; i < 2; i++)
        pthread_join(p[i], nullptr);
    delete rq;
    return 0;
}